//
//  WaitTakeDetail.m
//  RRQS
//
//  Created by kyjun on 16/3/28.
//
//

#import "WaitTakeDetail.h"
#import "MOrder.h"
#import "MStore.h"
#import "OrderDetailCell.h"
#import "OrderDetailHeader.h"
#import "OrderDetailFooter.h"
#import "MapNavgation.h"
#import "GoogleMaps.h"

@interface WaitTakeDetail ()<OrderDetailFooterDelegate>

@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UILabel* labelOrderNO;

@property(nonatomic,strong) UIView* lineView;
@property(nonatomic,strong) UILabel* labelMark;

@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;

@end

@implementation WaitTakeDetail

-(instancetype)init{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self){
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    
    self.cellIdentifier = @"OrderDetailCell";
    self.headerIdentifier = @"OrderDetailHeader";
    self.footerIdentitifer = @"OrderDetailFooter";
    
    [self layoutUI];
    [self layoutConstraints];
    [self refreshDataSource];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  User interface layout
-(void)layoutUI{
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80.f)];
    self.headerView.backgroundColor = [UIColor colorWithRed:255/255.f green:255/255.f blue:255/255.f alpha:1.0];
    [self.headerView addSubview:self.labelOrderNO];
    [self.headerView addSubview:self.lineView];
    [self.headerView addSubview:self.labelMark];
    self.tableView.tableHeaderView = self.headerView;
    [self.tableView registerClass:[OrderDetailCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[OrderDetailHeader class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[OrderDetailFooter class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
-(void)layoutConstraints{
    self.labelOrderNO.translatesAutoresizingMaskIntoConstraints = NO;
    self.lineView.translatesAutoresizingMaskIntoConstraints = NO;
    self.labelMark.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.labelOrderNO addConstraint:[NSLayoutConstraint constraintWithItem:self.labelOrderNO attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH-20.f]];
    [self.labelOrderNO addConstraint:[NSLayoutConstraint constraintWithItem:self.labelOrderNO attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelOrderNO attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelOrderNO attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
    [self.lineView addConstraint:[NSLayoutConstraint constraintWithItem:self.lineView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH]];
    [self.lineView addConstraint:[NSLayoutConstraint constraintWithItem:self.lineView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.lineView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.labelOrderNO attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.lineView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    
    [self.labelMark addConstraint:[NSLayoutConstraint constraintWithItem:self.labelMark attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH-20.f]];
    [self.labelMark addConstraint:[NSLayoutConstraint constraintWithItem:self.labelMark attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelMark attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelMark attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
}
#pragma mark =====================================================  Data source
-(void)queryData{
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"get_order_info",@"order_id":self.waiMaiDodelHList.order_id,@"emp_id":[UserModel sharedInstanced].userId};
//    NSDictionary* arg = @{@"ince":@"get_order_infos",@"main_id":self.waiMaiDodelListitems.order_id,@"emp_id":[UserModel sharedInstanced].userId};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSDictionary* dict = [responseObject objectForKey:@"order"];
            if(![WMHelper isNULLOrnil:dict]){
                self.entity = [[MOrder alloc]initWithStore:dict];
            }
            [self loadData];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }else{
            [self alertHUD:[responseObject objectForKey:@"fail"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
    }];
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [weakSelf queryData];
    }];
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return self.entity.arrayStore.count;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    MStore* empty =self.entity.arrayStore[section];
//    return empty.arrayGoods.count;
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
//    MStore* empty =self.entity.arrayStore[indexPath.section];
//    cell.entity =empty.arrayGoods[indexPath.row];
    return cell;
}

#pragma mark =====================================================  <UITableVeiwDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    MStore* empty =self.entity.arrayStore[indexPath.section];
//    MFood* item =empty.arrayGoods[indexPath.row];
//    CGFloat height = [WMHelper calculateTextHeight:item.foodName font:[UIFont systemFontOfSize:14.f] width:SCREEN_WIDTH*3/5];
//    return height + 10.f;
    return 60;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 230.f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    OrderDetailHeader* header =  (OrderDetailHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifier];
//    header.entity = self.entity.arrayStore[section];
    return header;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    OrderDetailFooter* footer = (OrderDetailFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerIdentitifer];
    footer.isWaitTask = self.isWaitTask;
//    MStore* item = self.entity.arrayStore[section];
//    footer.addressRoad = self.entity.addressRoad;
//    if(self.isWaitTask){
//        footer.address = item.storeAddress;
//    }else{
//        footer.address = self.entity.address;
//    }
//    footer.entity = item;
    footer.delegate = self;
    return footer;
}

#pragma mark =====================================================  <OrderDetailFooterDelegate>
-(void)orderDetailEnum:(EnumOrderAction)orderAction phone:(NSString *)phone{
    switch (orderAction) {
        case connectionBusiness:
        case connectionClient:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否拨打电话？" message:phone delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
            break;
        case confirmTake:
        {
            
        }
            break;
            
        default:
            break;
    }
}

-(void)orderDetailTake:(MStore *)item{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
    [self.view.window addSubview:self.HUD];
    self.HUD.delegate = self;
    self.HUD.minSize = CGSizeMake(135.f, 135.f);
    self.HUD.label.font = [UIFont systemFontOfSize:14.f];
    [self.HUD showAnimated:YES];
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"qs_get_food",@"emp_id":self.Identity.userInfo.userID,@"order_id":item.subOrderID};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(flag == 1){
            [self hidHUD:@"成功!" success:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationHomeRefreshing object:nil];
//            [self queryData];
        }else{
            NSLog(@"%@",[responseObject objectForKey:@"fail"]);
            [self hidHUD:[responseObject objectForKey:@"fail"]];
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.description);
        [self hidHUD:@"网络异常"];
    }];
}

-(void)locationMapLocation:(MStore *)item{
    if(self.isWaitTask){//待取货
        if([WMHelper isEmptyOrNULLOrnil:item.lat] || [WMHelper isEmptyOrNULLOrnil:item.lng]){
            [self alertHUD: @"取货坐标不全！"];
        }else{
//            MapNavgation* controller = [[MapNavgation alloc]initWithat:item.lat andLng:item.lng];
//            [self.navigationController pushViewController:controller  animated:YES];
            
            CLLocationDegrees latitude = ABS([item.lat doubleValue]);
            CLLocationDegrees longitude = ABS([item.lng doubleValue]);
            CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
            [self openGoogleMapsWithCoordinate:coordinate];
        }
    }else {//配送中
        if([WMHelper isEmptyOrNULLOrnil:item.phoneAddress]){
            [self alertHUD: @"配送坐标不全！"];
        }else{
            NSArray* empty = [item.phoneAddress componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
            if(empty.count == 2){
//                MapNavgation* controller = [[MapNavgation alloc]initWithat:[empty lastObject] andLng:[empty firstObject]];
//                [self.navigationController pushViewController:controller  animated:YES];
                
                CLLocationDegrees latitude  = ABS([[empty lastObject] doubleValue]);
                CLLocationDegrees longitude = ABS([[empty firstObject] doubleValue]);
                CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
                [self openGoogleMapsWithCoordinate:coordinate];
            }else{
                [self alertHUD: @"配送坐标不全！"];
            }
        }
    }
}

/**
 调起谷歌地图

 @param coordinate 坐标
 */
- (void)openGoogleMapsWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    if ([GoogleMaps isGoogleMapsInstalled]) {
        [GoogleMaps openGoogleMapsToCoordinate:coordinate];
    }
    else {
        [[[UIAlertView alloc] initWithTitle:@"提示"
                                    message:@"您尚未安装谷歌地图APP" delegate:nil
                          cancelButtonTitle:@"好" otherButtonTitles:nil, nil] show];
    }
}

#pragma mark =====================================================  <UIAlertViewDelegate>
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",alertView.message]]];
    }
}

#pragma mark =====================================================  private method
-(void)loadData{
    self.labelOrderNO.text = [NSString stringWithFormat:@"总订单号 : %@",self.entity.rowID];
    NSString* strMark = [NSString stringWithFormat:@"备注 : %@",self.entity.orderMark];
    NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:strMark];
    [attributeStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:[strMark rangeOfString:self.entity.orderMark]];
    self.labelMark.attributedText = attributeStr;
}


#pragma mark =====================================================  property package
-(MOrder *)entity{
    if(!_entity){
        _entity = [[MOrder alloc]init];
    }
    return _entity;
}

-(UILabel *)labelOrderNO{
    if(!_labelOrderNO){
        _labelOrderNO = [[UILabel alloc]init];
        _labelOrderNO.font = [UIFont systemFontOfSize:14.f];
        _labelOrderNO.textColor =[UIColor colorWithRed:152/255.f green:152/255.f blue:152/255.f alpha:1.0];
    }
    return _labelOrderNO;
}

-(UIView *)lineView{
    if(!_lineView){
        _lineView = [[UIView alloc]init];
        _lineView.backgroundColor = [UIColor colorWithRed:241/255.f green:241/255.f blue:241/255.f alpha:1.0];
    }
    return _lineView;
}

-(UILabel *)labelMark{
    if(!_labelMark){
        _labelMark = [[UILabel alloc]init];
        _labelMark.font = [UIFont systemFontOfSize:14.f];
        _labelMark.textColor = [UIColor colorWithRed:152/255.f green:152/255.f blue:152/255.f alpha:1.0];
    }
    return _labelMark;
}

@end
